package kafeisc.web.servlet.client;


import kafeisc.utils.DataSourceUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;


/**
 * @Classname ${NAME}
 * @Description TODO
 * @Date 2020/5/12 21:29
 * @Created 
 */
@WebServlet(name = "retrievePasswordServlet")
public class retrievePasswordServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 获取输入的用户名
        String username = request.getParameter("username");

        String sql = "select password,email from user where username='" + username + "'";
        String passwordSelect = "";
        String email = "";
        try {
            Connection conn = DataSourceUtils.getConnection();
            PreparedStatement pstm1 = conn.prepareStatement(sql);
            ResultSet rs = pstm1.executeQuery();
            while (rs.next())
            {
                passwordSelect = rs.getString("password");
                email = rs.getString("email");
                if(passwordSelect.equals(""))
                {

                }
                else
                {

                    // 发送邮件
                    String emailMsg = "尊敬的 " + username + " 您的密码为 : " + passwordSelect;
                    // 创建一个HtmlEmail 实例对象
                    HtmlEmail send = new HtmlEmail();
                    send.setHostName("smtp.qq.com");
                    send.setAuthentication("coffeebook_01@qq.com","ihirzcpnwxmtdcfe");
                    send.setFrom("2859883646@qq.com","咖啡书城");
                    send.setSSLOnConnect(true);
                    send.setCharset("utf-8");
                    send.addTo(email);
                    send.setSubject("密码找回");
                    send.setHtmlMsg(emailMsg);
                    send.send();
                    rs.close();
                    pstm1.close();
                    conn.close();
                    response.sendRedirect(request.getContextPath() + "/client/passwordSuccess.jsp");
                    return;
                }
            }
            rs.close();
            pstm1.close();
            conn.close();
            response.sendRedirect(request.getContextPath() + "/client/passwordFail.jsp");
            return;
        } catch (SQLException | EmailException e) {
            e.printStackTrace();
            response.sendRedirect(request.getContextPath() + "/client/passwordFail.jsp");
            return;
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
